import { Popup } from 'antd-mobile'
import React, { useState } from 'react'
import FilterFooter from '../../../../components/FilterFooter'
import styles from './index.module.css'

// 弹出框样式
const bodyStyle = {
  width: '80vw',
  display: 'flex',
  flexDirection: 'column',
  justifyContent: 'space-between',
  flex: 1
}

export default function FilterMore(props) {
  const { roomType, oriented, floor, characteristic } = props.data
  const { onSave, visible, handleVisible, defaultValue } = props

  // 选中项数组
  const [selectedValues, setSelectedValues] = useState(defaultValue)

  // 点击标签切换样式
  function onTagClick(value) {
    const newSelectedValues = [...selectedValues]
    if (!selectedValues.includes(value)) {
      // 没有当前项的值
      newSelectedValues.push(value)
    } else {
      // 有
      const index = newSelectedValues.findIndex(item => item === value)
      newSelectedValues.splice(index, 1)
    }
    setSelectedValues(newSelectedValues)
  }

  // 渲染标签
  function renderFilters(data) {
    return data.map(item => {
      const isSelected = selectedValues.includes(item.value) ? styles.tagActive : ''
      return (
        <span
          className={[styles.tag, isSelected].join(' ')}
          key={item.value}
          onClick={() => onTagClick(item.value)}
        >
          {item.label}
        </span>
      )
    })
  }

  // 取消按钮的事件处理函数
  function onCancel() {
    setSelectedValues([])
  }

  // 确定按钮的实际处理函数
  function onOk() {
    // 调用父组件中的 onSave 方法
    onSave(selectedValues)
    handleVisible()
  }

  return (
    <Popup visible={visible} onMaskClick={handleVisible} position="right" bodyStyle={bodyStyle}>
      {/* 选项标签 */}
      <div className={styles.tags}>
        <div className={styles.name}>户型</div>
        <div className={styles.child}>{renderFilters(roomType)}</div>

        <div className={styles.name}>楼层</div>
        <div className={styles.child}>{renderFilters(oriented)}</div>

        <div className={styles.name}>朝向</div>
        <div className={styles.child}>{renderFilters(floor)}</div>

        <div className={styles.name}>特色</div>
        <div className={styles.child}>{renderFilters(characteristic)}</div>
      </div>

      {/* 底部按钮 */}
      <FilterFooter className={styles.footer} cancelText="清除" onCancel={onCancel} onOk={onOk} />
    </Popup>
  )
}
